from pathlib import Path
from requests import Session
from queue import Queue

session = Session()
session.headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 Edg/92.0.902.67"}
download_queue = Queue()

def add_task(url:str,save_path:str):
    if url is None or url == "":
        raise ValueError("url不能为空")
    if url.startswith("//"):
        url=f"https:{url}"
    download_queue.put({"url":url,"save_path":save_path})

def start_download():
    while download_queue.qsize()>0:
        task = download_queue.get()
        download(task["url"], task["save_path"])

def download(url:str,file_name:str):
    """ 下载 """
    print(f"正在下载:{url}")
    resp=session.get(url)
    path=Path(file_name)
    path.parent.mkdir(parents=True,exist_ok=True)
    with open(file_name,"wb") as f:
        f.write(resp.content)